#include "pch.hpp"
#include "WidgetImpl.hpp"




WinUi::Widget::impl::impl(const std::wstring& className)
	: className(className)
	, wnd(0)
{
	ZeroMemory(&wc, sizeof(wc));

	HINSTANCE hInstance = GetModuleHandle(NULL);

	// Test if it's a system class
	if(GetClassInfoEx(NULL, className.c_str(), &wc) != 0)
	{
		// Nothing to do
	}
	// The class could have been previously registered
	else if(GetClassInfoEx(hInstance, className.c_str(), &wc) != 0)
	{
		// Nothing to do
	}
	// The class doesn't exist yet: create it
	else
	{
		wc.cbSize = sizeof(WNDCLASSEX);                  // size of the window struct in bytes
		wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;   // window styles to use
		wc.lpfnWndProc = msgProc;                        // function name of event handler
		wc.hInstance = GetModuleHandle(NULL);            // handle to this apps instance
		wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);      // icon for the app window
		wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);    // icon when minimized to taskbar
		wc.hCursor = LoadCursor(NULL, IDC_ARROW);        // cursor to use for this window
		wc.lpszClassName = this->className.c_str();

		// Register the window class
		RegisterClassEx(&wc);
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////

LRESULT WINAPI WinUi::Widget::impl::msgProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	// Extract the user data for the given window which is actually a pointer to a window,
	// then forward to the actual member function.
	// However the pointer is not set, when the WM_CREATE message arrives, so call the default
	// handler in this case
	Widget* widget = reinterpret_cast<Window*>(GetWindowLongPtr(wnd, GWLP_USERDATA));
	if(widget)
		return widget->msgProc(msg, wParam, lParam);
	else
		return DefWindowProc(wnd, msg, wParam, lParam);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
